<template>
  <div>
    <t-dialog
      width="auto"
      class="dialog"
      placement="center"
      :header="false"
      :footer="false"
      :closeBtn="false"
      :visible.sync="visible"
      :close-on-overlay-click="false"
    >
      <template #header>
        <div class="flex align-center justify-between" style="width: 100%;">

        </div>
      </template>
      <!--<template #footer>-->
      <!--  <div class="footer-btn">-->
      <!--    <t-button theme="danger" variant="outline" class="danger-btn">取消出库</t-button>-->
      <!--    <t-space size="8px">-->
      <!--      <t-button theme="default" class="cancel-btn" @click="close">取消</t-button>-->
      <!--      <t-button theme="primary" class="confirm-btn" @click="close">确定</t-button>-->
      <!--    </t-space>-->
      <!--  </div>-->
      <!--</template>-->
      <div class="dialog-body">
        <div class="left">
          <div class="drawer-head" @click="close">
            <h3>{{header}}</h3>
          </div>

          <div class="product-info">
            <h3>{{ row.title }}</h3>
            <!--<p>售价：¥13894.00</p>-->
          </div>

          <t-form :data="formData" :rules="rules" ref="form" layout="inline" label-align="top" @submit="onSubmit">
            <t-form-item name="unit_price" style="flex: 1;margin-right: 18px;">
              <template #label>
                <p class="form-label2">调拨价</p>
              </template>
              <t-input label="￥" v-model="formData.unit_price" placeholder="¥ 0.00"></t-input>
            </t-form-item>
            <t-form-item name="quantity" style="width: 168px;margin-right: 18px;">
              <template #label>
                <p class="form-label2">数量</p>
              </template>
              <t-input-number v-model="formData.quantity" :min="0" placeholder="请输入"></t-input-number>
            </t-form-item>
            <t-form-item name="unit_id" style="width: 160px;margin-right: 0;">
              <template #label>
                <p class="form-label2">单位</p>
              </template>
              <t-select v-model="formData.unit_id" :options="unitOptions" placeholder="选择产品单位" />
            </t-form-item>
            <t-form-item name="remark" style="width: 100%;margin-right: 0;">
              <template #label>
                <p class="form-label2">备注</p>
              </template>
              <t-textarea v-model="formData.remark" :maxlength="50" placeholder="请输入备注" />
            </t-form-item>
            <t-form-item style="width: 100%;margin-right: 0;">
              <template #label>
                <div class="flex align-center">
                  <p class="form-label2">SN码</p>
                  <p class="label-hint">(已录数量：29)</p>
                  <t-switch v-model="formData.is_sn" :label="['开启', '关闭']" :custom-value="[1, 0]" style="margin-left: 8px;"></t-switch>
                </div>
              </template>
              <div v-if="formData.is_sn === 1" style="width: 100%;">
                <t-table
                  rowKey="id"
                  :data="formData.sn_data"
                  :columns="columns"
                  :stripe="stripe"
                  :bordered="bordered"
                  :hover="hover"
                  :size="size"
                  :max-height="maxHeight"
                  :table-layout="tableLayout ? 'auto' : 'fixed'"
                  :showHeader="showHeader"
                  cellEmptyContent="-"
                  resizable
                  :loading="loading"
                >
                  <template #title-slot-sn>
                    <div class="flex align-center">
                      <p>SN码</p>
                      <t-popconfirm :visible="batchVisible" placement="top-left" @confirm="confirmSN" @visible-change="onVisibleChange">
                        <template #icon><p></p></template>
                        <template #content>
                          <div style="width: 360px">
                            <t-form :data="batchFormData" :rules="batchRules" ref="batchForm" layout="inline" label-align="top" @submit="onBatchSubmit">
                              <t-form-item name="codes" style="flex: 1;margin-right: 18px;">
                                <template #label>
                                  <p class="form-label2">批量录入SN码</p>
                                </template>
                                <t-textarea v-model="batchFormData.codes" placeholder="请输入SN,使用','号分割"></t-textarea>
                              </t-form-item>
                            </t-form>
                          </div>
                        </template>
                        <t-link class="edit-btn-color ml8" hover="color">批量录入</t-link>
                      </t-popconfirm>
                    </div>
                  </template>
                  <template #option="{row}">
                    <t-button theme="danger" variant="outline" @click="handleDelete(row)">删除</t-button>
                    <!--<t-link class="edit-btn-color" hover="color" @click="showInventory = !showInventory">增加配件清单(0)</t-link>-->
                  </template>
                </t-table>
              </div>
            </t-form-item>
          </t-form>
            <div class="footer-btn">
              <div>
                <t-button theme="danger" v-if="type === 'again'" variant="outline" class="danger-btn" @click="cancelWarehousing">取消出库</t-button>
              </div>
              <t-space size="8px">
                <t-button theme="primary" class="confirm-btn" @click="confirmWarehousing">确定</t-button>
                <t-button theme="default" class="cancel-btn" @click="close">取消</t-button>
              </t-space>
            </div>
        </div>

        <!-- 右侧 -->
        <config-right v-if="showInventory"></config-right>

      </div>
    </t-dialog>
  </div>
</template>

<script>
import { IconFont } from "tdesign-icons-vue";
import ConfigRight from "@/pages/warehouse/allocation/components/config-right.vue";
import {classifyListApi} from "@/api/classify";

export default {
  name: 'ConfigInfo',
  props: {
    order_type: {
      type: Number,
      default: 0
    }
  },
  components: {ConfigRight, IconFont},
  data() {
    return {
      visible: false,
      header: '填写调拨信息',
      confirmBtn: {
        text: '保存',
        theme: 'primary',
        loading: false
      },
      row: {},
      showInventory: true,
      formData: {
        product_id: '', // 产品ID
        unit_id: '',  // 单位ID
        quantity: '', // 数量两位小数
        is_sn: 1, // 开启SN序列号（0关闭；1开启）
        sn_data: [], // SN数据
        unit_price: '', // 含税单价（进货价）
        remark: '', // 备注（50个字内）
      },
      rules: {
        unit_price: [{ required: true, message: '请输入进货价', trigger: 'blur' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'change' }],
        unit_id: [{ required: true, message: '请输入产品单位', trigger: 'change' }],
      },
      unitOptions: [],
      switchValue: true,
      type: 'first',

      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        {colKey: 'index', title: '序号', align: 'center', width: 62,},
        {colKey: 'sn', title: 'title-slot-sn' },
        {colKey: 'option', title: '操作', fixed: 'right', width: 80},
      ],
      maxHeight: 200,
      loading: false,

      batchVisible: false,
      batchFormData: {
        codes: ''
      },

      batchRules: {
        codes: [{ required: true, message: '请输入SN,使用","号分割', trigger: 'blur' }],
      },
      orderType: {
        0: '入库',
        1: '出库',
        2: '调拨',
        3: '盘点'
      },
    }
  },
  methods: {
    onVisibleChange(val, context = {}) {
      // trigger 表示触发来源，可以根据触发来源自由控制 visible
      if (context && context.trigger !== 'confirm') {
        this.batchVisible = val;
      }
    },
    confirmSN() {
      this.$refs.batchForm.submit();
    },
    onBatchSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        // 对codes进行处理,按照，,进行分割
        let codes = this.batchFormData.codes.replace(/\n/g,'');
        codes = codes.split(',')
        if (codes.length !== this.formData.quantity) {
          this.$message.error('产品数量和SN码数量不一致')
          return
        }
        this.formData.sn_data = codes.map((item, index) => ({ index: (index+1), sn: item })).filter(item=> item.sn)
        this.batchVisible = false
      } else {
        this.$message.warning(firstError);
      }
    },
    handleDelete(row) {
      this.formData.sn_data = this.formData.sn_data.filter(item=> item.index !== row.index)
    },
    // 取消出库
    cancelWarehousing() {
      this.$emit('cancel', this.formData)
      this.close();
    },
    // 确认出库
    confirmWarehousing() {
      if (this.formData.sn_data.length !== this.formData.quantity) {
        this.$message.error('产品数量和SN码数量不一致')
        return
      }
      this.$emit('confirm', this.formData)
      this.close();
    },
    onSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        this.$message.success('提交成功');
      } else {
        console.log('Errors: ', validateResult);
        this.$message.warning(firstError);
      }
    },
    // 获取列表
    getList() {
      const params = {
        page: 1,  // 当前页
        limit: 9999,  // 每页条数
        belong_module: 'product_unit',
      }
      classifyListApi(params).then(res=> {
        this.unitOptions = res.data.map(item=> ({ label: item.title, value: item.id }))
      }).catch(err=> {
        console.log('err', err)
      })
    },
    open(type='first', row) {
      this.row = row
      this.type = type
      this.showInventory = false
      this.visible = true
      this.formData = {
        ...row,
        product_id: row.product_id, // 产品ID
        unit_id: row.unit_id || '',  // 单位ID
        quantity: row.quantity || 0, // 数量两位小数
        is_sn: row.is_sn || 0,
        sn_data: row.sn_data || [],
        unit_price: row.unit_price || '',
        remark: row.remark || '',
      }

      this.header = '填写调拨信息'
      this.batchFormData = {
        codes: ''
      }
      this.getList()
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>

/deep/ .dialog {
  .t-dialog--default {
    padding: 0;

    .t-dialog__body {
      padding: 0;
    }
  }
}

.dialog-body {
  display: flex;
}

.form-label2 {
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  color: #000000E5;
}

.label-hint {
  font-size: 12px;
  font-weight: 400;
  line-height: 16.8px;
  padding-left: 8px;
  padding-right: 8px;
  color: var(--td-font-gray-2);
}

/deep/ .t-dialog__body {
  margin: 0 !important;
}

/deep/ .dialog-body {

  .t-input.t-size-l {
    min-height: 40px !important;
  }

  .t-input-number.t-size-l .t-input {
    font-size: 17px;
    min-height: 40px;
  }

  .t-input {
    background-color: #FFFFFF !important;
  }

}


/deep/ .left {
  position: relative;
  width: 640px;
  padding: 32px 24px;
  padding-bottom: 24px;
  box-sizing: border-box;


  .drawer-head {
    color: black;
  }

  .product-info {
    padding: 12px;
    margin-top: 12px;
    margin-bottom: 24px;
    background-color: #F9F9F9;
    border-radius: var(--td-radius-medium);

    h3 {
      font-size: 16px;
      font-weight: 600;
      line-height: 22.4px;
      text-align: left;
      color: #000000;
    }

    p {
      font-size: 16px;
      font-weight: 400;
      line-height: 24px;
      text-align: left;
      color: #000000E5;
    }
  }
}


.footer-btn {
  width: 100%;
  display: flex;
  padding-top: 24px;
  align-items: center;
  justify-content: space-between;
}

.danger-btn {
  width: 112px;
  height: 40px;
  border-radius: var(--td-radius-medium);
}

.confirm-btn {
  width: 82px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 400;
  line-height: 22.4px;
  border-radius: var(--td-radius-medium);
}

.cancel-btn {
  width: 82px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 400;
  line-height: 22.4px;
  background-color: #B8B8B8;
  border-radius: var(--td-radius-medium);
}

.cancel-btn2 {
  width: 82px;
  height: 42px;
  font-size: 16px;
  font-weight: 400;
  line-height: 22.4px;
  border-radius: var(--td-radius-medium);
}
</style>
